package render

import (
	"fmt"

	db "gsc-datasets/internal/db/dao"

	"github.com/go-chi/render"
)

func ErrInvalidRequest(friendlyMsg string) render.Renderer {
	return &AppBaseResponse{
		HTTPStatusCode: 400,
		StatusText:     "Invalid request.",
		ErrorText:      friendlyMsg,
	}
}

func ErrBadRequest(err error) render.Renderer {
	return &AppBaseResponse{
		Err:            err,
		HTTPStatusCode: 400,
		StatusText:     "Bad request.",
		ErrorText:      err.Error(),
	}
}

func ErrInvalidPath(err error) render.Renderer {
	return &AppBaseResponse{
		Err:            err,
		HTTPStatusCode: 400,
		StatusText:     "Invalid path.",
		ErrorText:      err.Error(),
	}
}

func ErrNotAuthorized(err error) render.Renderer {
	return &AppBaseResponse{
		Err:            err,
		HTTPStatusCode: 400,
		StatusText:     "Not Authorized.",
		ErrorText:      err.Error(),
	}
}

func ErrNotFoundRender(err error) render.Renderer {
	return &AppBaseResponse{
		Err:            err,
		HTTPStatusCode: 404,
		StatusText:     "Resource not found.",
		ErrorText:      err.Error(),
	}
}

func ErrUpstreamInvokeRender(err error) render.Renderer {
	return &AppBaseResponse{
		Err:            err,
		HTTPStatusCode: 400,
		StatusText:     "upstream invoke fail.",
		ErrorText:      err.Error(),
	}
}

func ErrDatabaseExec(err error, friendlyMsg string) render.Renderer {
	return &AppBaseResponse{
		Err:            err,
		HTTPStatusCode: 400,
		StatusText:     "执行数据库错误.",
		ErrorText:      friendlyMsg,
	}
}

func ErrRender(err error) render.Renderer {

	pgErrPtr := db.ExtractPgCode(&err)
	if pgErrPtr != nil {
		//
		pgErrCodeName := pgErrPtr.Code.Name()
		fmt.Println("pgerr code=>", pgErrPtr.Code, ", code name=>", pgErrCodeName)
		var friendlyMsg string
		switch pgErrCodeName {
		case "unique_violation":
			friendlyMsg = "违反唯一约束"
		default:
			friendlyMsg = err.Error()
		}
		return ErrDatabaseExec(err, friendlyMsg)
	} else {
		
		r := &AppBaseResponse{
			Err:            err,
			HTTPStatusCode: 500,
			StatusText:     "内部错误",
			ErrorText:      "内部错误",
		}
		// fmt.Println("ErrRender=>", r)
		return r
	}
}

// var ErrNotFound = &MockResponse{HTTPStatusCode: 404, StatusText: "Resource not found."}
